<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>轨迹视角</title>
  <link href="./css/index.css" rel="stylesheet">
  <style type="text/css">
    ul li {
      list-style: none;
    }

    .drawing-panel {
      z-index: 999;
      position: fixed;
      bottom: 3rem;
      margin-left: 1rem;
      padding: 1rem 1rem;
      border-radius: .25rem;
      background-color: #fff;
      box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
    }

    .drawing-panel li {
      float: left;
    }

    .drawing-panel select {
      padding: 5px;
      width: 97px;
    }

    .btn {
      background-color: #fff;
      color: rgba(27, 142, 236, 1);
      font-size: 14px;
      border: 1px solid rgba(27, 142, 236, 1);
      border-radius: 5px;
      padding: 4px 8px;
      user-select: none;
    }

    .btn:hover {
      background-color: rgba(27, 142, 236, 0.8);
      color: #fff;
    }
  </style>
</head>

<body>
  <div class="drawing-panel" style="z-index: 99;">
    <input type="datetime-local" id="txtStartTime" />
    <br />
    <input type="datetime-local" id="txtEndTime" style="margin:10px 0;" />
    <div>
      <select id="device"></select>
      <button id="btnStart" class="btn" onclick="startAni()">查看轨迹</button>
    </div>
  </div>
  <script src="./js/gcoord.js"></script>
  <script src="./js/lib.js"></script>
  <script src="./js/ha.js"></script>
  <script>
    const select = document.querySelector('#device')
    const btnStart = document.querySelector('#btnStart')
    select.addEventListener('change', async () => {
      ha.trackAni?.cancel()
      const entityId = select.value
      const state = ha.hass.states[entityId]
      const { longitude, latitude, map, entity_picture, friendly_name } = state.attributes

      let [lng, lat] = ha.transform([longitude, latitude], map === 'gaode' ? gcoord.GCJ02 : gcoord.WGS84, gcoord.BD09)
      ha.readerMarker(({ hass }) => {
        ha.addIconMarker(lng, lat, { entityId, entity_picture, friendly_name })
        ha.centerAndZoom(lng, lat, 17);
      })
    })

    ha.loadMap().then(async ({ hass }) => {
      ha.loadScript("https://mapopen.bj.bcebos.com/github/BMapGLLib/TrackAnimation/src/TrackAnimation.min.js")
      ha.centerAndZoom(ha.lng, ha.lat, 17);

      // 初始化时间
      const today = new Date()
      today.setHours(today.getHours() + 8)
      const endTime = today.toISOString()
      today.setDate(today.getDate() - 1)
      const startTime = today.toISOString()
      document.querySelector('#txtStartTime').value = startTime.substring(0, 16)
      document.querySelector('#txtEndTime').value = endTime.substring(0, 16)

      // 获取设备
      Object.keys(hass.states).filter(ele => ['person', 'device_tracker'].includes(ele.split('.')[0])).forEach(entity_id => {
        const { friendly_name } = hass.states[entity_id].attributes

        const option = document.createElement('option')
        option.text = friendly_name
        option.value = entity_id
        select.appendChild(option)
      })

    })

    let loading = false
    function startAni() {
      console.log(select.value)
      let startTime = document.querySelector('#txtStartTime').value
      let endTime = document.querySelector('#txtEndTime').value
      console.log(startTime, endTime)
      if (!startTime || !endTime) {
        return parent.alert("请选择要查看的开始和结束时间")
      }
      // 获取坐标点
      if (loading) {
        return
      }
      loading = true
      getPoints(select.value, new Date(startTime).toISOString(), new Date(endTime).toISOString()).then((arr) => {
        loading = false
        if (arr.length < 2) return parent.alert("必须得有两个定位点才能使用")
        ha.startTrack(arr)
      })
    }

    function getPoints(entity_id, start_time, end_time) {
      return new Promise((resolve) => {
        ha.hass
          .fetchWithAuth(`/api/history/period/${start_time}?filter_entity_id=${entity_id}&end_time=${end_time}`)
          .then(res => res.json()).then(res => {
            if (res.length == 0) resolve([])

            const list = res[0].filter(ele => ele.state !== 'unknown'
              && ele.attributes && ele.attributes.latitude && ele.attributes.longitude)
            const points = list.map(({ attributes: { latitude, longitude, map } }) => {
              return ha.transform([longitude, latitude], map === 'gaode' ? gcoord.GCJ02 : gcoord.WGS84, gcoord.BD09)
            })
            resolve(points)
          })
      })
    }



  </script>
</body>

</html>